<?php
// 设置允许的来源，这里假设允许来自 http://1.13.198.191:8081 的请求
// header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
header("Access-Control-Allow-Origin: *");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "./conn.php";
require_once "./usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 500, "Msg" => "连接错误: " . $conn->connect_error]));
}
// -----获取设备列表---
// 获取前端传递的 JSON 数据
$data = json_decode(file_get_contents("php://input"), true);

// 获取设备列表（带分页）
$page = isset($data['page']) ? intval($data['page']) : 1;
$pageSize = isset($data['pageSize']) ? intval($data['pageSize']) : 25;

$offset = ($page - 1) * $pageSize;

$sql = "SELECT * FROM devices LIMIT $offset, $pageSize";
$result = $conn->query($sql);

$devices = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $devices[] = $row;
    }
}

$sqlCount = "SELECT COUNT(*) as total FROM devices";
$resultCount = $conn->query($sqlCount);
$totalCount = $resultCount->fetch_assoc()['total'];

echo json_encode(['Code' => 200, 'Msg' => '获取设备列表成功', 'Ret' => true, 'Data' => $devices, 'Total' => $totalCount]);

?>
